package com.fiveGroup.controller;


import com.fiveGroup.pojo.ProductReview;
import com.fiveGroup.pojo.vo.DataVo;
import com.fiveGroup.pojo.vo.ProductReviewVo;
import com.fiveGroup.service.ProductReviewService;
import com.fiveGroup.util.UserContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/api/review")
@Slf4j
@RequiredArgsConstructor
public class ReviewController {

    private final ProductReviewService reviewService;

    // 展示某件商品所有评论
    @GetMapping("/getReviewList")
    public DataVo getReviewList(@RequestParam Long productId) {
        try {
            // 调用服务层方法获取评论列表
            List<ProductReviewVo> reviewList = reviewService.selectByProductId(productId);

            return DataVo.success(reviewList);
        } catch (Exception e) {
            // 处理异常并返回错误信息
            return DataVo.fail("获取评论列表失败：" + e.getMessage());
        }
    }

    // 删除某个商品的评论
    @PostMapping("/deleteReview")
    public DataVo deleteReview(@RequestParam Long id) {

        int isDelete = reviewService.deleteReview(id);

        return isDelete > 0 ? DataVo.success("删除成功") : DataVo.fail("删除失败");


    }


    // 添加某个商品的评论
    @PostMapping("/addReview")
    public DataVo addReview(@RequestBody ProductReview productReview) {

        // 获取当前上下文用户id
        Long userId = UserContextHolder.getUserId();
        if (userId == null) {
            return DataVo.fail("用户未登录");
        }


        ProductReview review = new ProductReview();
        review.setUserId(userId);
        review.setComment(productReview.getComment());
        review.setCreatedAt(LocalDate.now());
        review.setRating(productReview.getRating());
        review.setOrderId(productReview.getOrderId());
        review.setProductId(productReview.getProductId());

        int isSave = reviewService.addReview(review);

        return isSave > 0 ? DataVo.success("添加成功") : DataVo.fail("添加失败");
    }
}
